package cn.stylefeng.guns.modular.hx.storage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPosition;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicPositionGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicPositionGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicPositionGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageMoveRecord;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStoragePutDetailed;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxStorageMoveRecordMapper;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageMoveRecordParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageMoveRecordResult;
import  cn.stylefeng.guns.modular.hx.storage.service.HxStorageMoveRecordService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStoragePutDetailedService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.rest.hxStorageStock.vo.StorageMoveCntItemVo;
import cn.stylefeng.guns.modular.rest.hxStorageStock.vo.StorageMoveCntVo;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.annotation.Resource;

/**
 * <p>
 * 移库记录表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-09-09
 */
@Service
public class HxStorageMoveRecordServiceImpl extends ServiceImpl<HxStorageMoveRecordMapper, HxStorageMoveRecord> implements HxStorageMoveRecordService {

    @Autowired
    private HxStorageStockService stockService;
    @Autowired
    private HxStorageMoveRecordService hxStorageMoveRecordService;
    @Autowired
    private HxStorageMoveRecordMapper recordMapper;
    @Autowired
    private BasicPositionService positionService;
    @Autowired
    private HxBasicPositionGoodsService positionGoodsService;
    @Autowired
    private HxBasicGoodsService goodsService;
    @Autowired
    private UserAop userAop;
    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    @Autowired
    private UserService userService;
    @Autowired
    private BasicAreaService basicAreaService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private BasicPositionService basicPositionService;
    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    @Resource
    private HxStoragePutDetailedService hxStoragePutDetailedService;
    @Resource
    private HxStorageStockService hxStorageStockService;

    @Override
    public void add(HxStorageMoveRecordParam param){
        HxStorageMoveRecord entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HxStorageMoveRecordParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxStorageMoveRecordParam param){
        HxStorageMoveRecord oldEntity = getOldEntity(param);
        HxStorageMoveRecord newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public HxStorageMoveRecordResult findBySpec(HxStorageMoveRecordParam param){
        return null;
    }

    @Override
    public List<HxStorageMoveRecordResult> findListBySpec(HxStorageMoveRecordParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxStorageMoveRecordParam param,Long operateId,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,operateId,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String removeStorage(HxStorageMoveRecordParam hxStorageMoveRecordParam, Long[] ids) {
        User user = userAop.getUser();
        //封装HxStorageMoveRecord
        HxStorageMoveRecord hxStorageMoveRecord = new HxStorageMoveRecord();
        BeanUtils.copyProperties(hxStorageMoveRecordParam,hxStorageMoveRecord);
        
        List<HxStorageStock> hxStorageStocks = stockService.lambdaQuery()
                .in(HxStorageStock::getId, ids)
                .list();
        if (ToolUtil.isEmpty(hxStorageStocks))
            return "error1";

        BasicPosition basicPosition = new BasicPosition();
        if(hxStorageMoveRecord.getNewPositionId() != null) {
            basicPosition = positionService.lambdaQuery()
            		.eq(BasicPosition::getWarehouseId, hxStorageStocks.get(0).getWarehouseId())
            		.eq(BasicPosition::getId, hxStorageMoveRecord.getNewPositionId())
                    .last("LIMIT 1")
                    .one();
        } else {
            basicPosition = positionService.lambdaQuery()
            		.eq(BasicPosition::getWarehouseId, hxStorageStocks.get(0).getWarehouseId())
                    .eq(BasicPosition::getPositionNumber, hxStorageMoveRecord.getNewPositionNumber())
                    .last("LIMIT 1")
                    .one();
        }
//        if(basicPosition.getPositionType().equals("存储位")){
//            Integer count = hxStorageStockService.lambdaQuery()
//                    .eq(HxStorageStock::getPositionNumber, hxStorageMoveRecord.getNewPositionNumber())
//                    .eq(HxStorageStock::getOperateId, user.getOperateId())
//                    .count();
//            if(count>0) {
//                return "error10";
//            }
//        }
        if (ToolUtil.isEmpty(basicPosition))
            return "error2";
        //赋值
        hxStorageMoveRecord.setNewPositionId(Long.valueOf(basicPosition.getId()));
        hxStorageMoveRecord.setNewPositionType(basicPosition.getPositionType());
        hxStorageMoveRecord.setNewPositionNumber(basicPosition.getPositionNumber());
        hxStorageMoveRecord.setAreaId(Long.valueOf(basicPosition.getPositionAreaId()));

        int i = hxStorageStocks.get(0).getWarehouseId().intValue();
        if (i!=basicPosition.getWarehouseId())
            return "error4";

        List<HxStorageMoveRecord> hxStorageMoveRecords=new ArrayList<>();
        HxStorageMoveRecord _hxStorageMoveRecord = null;
        List<Long> longs=new ArrayList<>();
        for (HxStorageStock hxStorageStock : hxStorageStocks) {
            List<String> list= recordMapper.findOutTask(hxStorageStock.getId().longValue());
            List<String> list1= new ArrayList<>();
            for (String s : list) {
                if (ToolUtil.isNotEmpty(s)){
                	if(s.equals("待拣货")||s.equals("拣货中")) {
                		list1.add(s);
                	}
                }
            }
            if (ToolUtil.isNotEmpty(list1))
                continue;
            _hxStorageMoveRecord = new HxStorageMoveRecord();
            BeanUtils.copyProperties(hxStorageMoveRecordParam,_hxStorageMoveRecord);

            _hxStorageMoveRecord.setOperateId(hxStorageStock.getOperateId());
            _hxStorageMoveRecord.setCustomerId(hxStorageStock.getCustomerId());
            _hxStorageMoveRecord.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
            _hxStorageMoveRecord.setWarehouseName(basicPosition.getWarehouseName());
            _hxStorageMoveRecord.setAreaId(Long.valueOf(basicPosition.getPositionAreaId()));
            _hxStorageMoveRecord.setOldPositionId(hxStorageStock.getPositionId());
            _hxStorageMoveRecord.setOldPositionNumber(hxStorageStock.getPositionNumber());
            _hxStorageMoveRecord.setOldPositionType(hxStorageStock.getPositionType());
            _hxStorageMoveRecord.setNewPositionId(Long.valueOf(basicPosition.getId()));
            _hxStorageMoveRecord.setNewPositionType(basicPosition.getPositionType());
            _hxStorageMoveRecord.setTrayId(hxStorageStock.getTrayId());
            _hxStorageMoveRecord.setTrayNumber(hxStorageStock.getTrayNumber());
            _hxStorageMoveRecord.setGoodsId(hxStorageStock.getGoodsId());
            _hxStorageMoveRecord.setGoodsName(hxStorageStock.getGoodsName());
            _hxStorageMoveRecord.setGoodsNumber(hxStorageStock.getGoodsNumber());
            _hxStorageMoveRecord.setGoodsPcode69(hxStorageStock.getGoodsPcode69());
            _hxStorageMoveRecord.setGoodsSpecs(hxStorageStock.getGoodsSpecs());
            _hxStorageMoveRecord.setKcUnit(hxStorageStock.getKcUnit());
            _hxStorageMoveRecord.setKcNum(hxStorageStock.getKcNum());
            _hxStorageMoveRecord.setTransferTime(LocalDateTime.now());
            _hxStorageMoveRecord.setDeptId(hxStorageStock.getDeptId());
//            if (!hxStorageStock.getDeptId().equals(basicPosition.getDeptId()))
//                throw new RuntimeException();
            longs.add(hxStorageStock.getId().longValue());
            BasicWarehouse w = basicWarehouseService.getById(basicPosition.getWarehouseId());
            BasicCustomer r = basicCustomerService.getById(_hxStorageMoveRecord.getCustomerId());
    		if(ToolUtil.isNotEmpty(r.getGsnumber())&&ToolUtil.isNotEmpty(r.getStoreIdXlb())) {
				if(ToolUtil.isNotEmpty(r.getModeTms())&&r.getModeTms().equals("3")&&hxStorageStock.getStockState().equals("正常")) {
		            if(ToolUtil.isEmpty(w.getWarehouseXlbId())) {
		                return String.format("请维护新零帮仓库id");
		            }
	                BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
	                oauth2tokenParam.setDeliverId(r.getDeliverId());
	                oauth2tokenParam.setGsnumber(r.getGsnumber());
	                BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
	                //String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.movestorage.save";
	                String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.movestorage.save";
	                LocalDate productionDate = LocalDate.parse(hxStorageStock.getDetailedDate());
	                // 保质期（以月份表示）
	                String shelfLifeMonths =hxStorageStock.getGoodsWarranty();
	                LocalDateTime outputDateTime = productionDate.atStartOfDay();

                    LocalDate expiryDate = productionDate.plusMonths(Integer.parseInt(shelfLifeMonths));
	                // 格式化输出到期日期
	                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	                LocalDateTime expiryDateTime = expiryDate.atStartOfDay();
	                String formattedExpiryDate = expiryDateTime.format(formatter);// 格式化输出到期日期
	                String deliveryDate = outputDateTime.format(formatter);// 格式化输出生产日期
	                JSONArray ordersArray = new JSONArray();
	                JSONObject orderObject = new JSONObject();
	                BasicPosition  basicPosition1= basicPositionService.lambdaQuery()
	                        .eq(BasicPosition::getId,_hxStorageMoveRecord.getNewPositionId() )
	                        .last("LIMIT 1")
	                        .one();
	                BasicPosition  basicPosition2= basicPositionService.lambdaQuery()
	                        .eq(BasicPosition::getId,_hxStorageMoveRecord.getOldPositionId() )
	                        .last("LIMIT 1")
	                        .one();
	                HxBasicGoods  hxBasicGoods= hxBasicGoodsService.lambdaQuery()
	                        .eq(HxBasicGoods::getId,_hxStorageMoveRecord.getGoodsId() )
	                        .last("LIMIT 1")
	                        .one();
	                BigDecimal jibennum = new BigDecimal( _hxStorageMoveRecord.getKcNum());
	                BigDecimal jibenrate = new BigDecimal(hxBasicGoods.getKcRate());
	                orderObject.put("basic_quantity",jibennum.multiply(jibenrate));//基本数量
	                orderObject.put("expire_date", formattedExpiryDate);//到期日期
	                orderObject.put("in_storage_id", basicPosition1.getPositionXlbId());//	移入库位id 必填
	                orderObject.put("item_code",_hxStorageMoveRecord.getGoodsNumber());//商品条码
	                orderObject.put("item_bar_code",_hxStorageMoveRecord.getGoodsPcode69());//商品代码
	                orderObject.put("item_id",hxBasicGoods.getGoodsXlbId());//商品id
	                orderObject.put("item_name",_hxStorageMoveRecord.getGoodsName());//商品名称
	                orderObject.put("item_spec",_hxStorageMoveRecord.getGoodsSpecs());//规格
	                orderObject.put("producing_date",deliveryDate);//生产日期
	                orderObject.put("quantity", _hxStorageMoveRecord.getKcNum());//数量 必填
	                orderObject.put("ratio", hxBasicGoods.getKcRate());//换算率 必填
	                orderObject.put("stock_detail_id", "");//库存明细id
	                orderObject.put("storage_id",basicPosition2.getPositionXlbId());//	移出库位id 必填
	                orderObject.put("store_id", r.getStoreIdXlb());//门店id 必填
	                orderObject.put("storehouse_id", w.getWarehouseXlbId());//仓库id 必填
	                orderObject.put("unit", _hxStorageMoveRecord.getKcUnit());//单位
	                ordersArray.put(orderObject);
	                JSONObject json = new JSONObject();
	                json.put("details", ordersArray);//明细
                    json.put("operator", user.getName());//操作人

                    //System.out.println(ordersArray);
	                //System.out.println(json);

	                String response = HttpRequest.post(url)
	                        .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
	                        .body(json.toString()).execute().body();
	                JSONObject jsonObject = new JSONObject(response);
	                if (jsonObject.get("code").toString().equals("0")) {
	                    //System.out.println(jsonObject.toString());
	                }else {
	                    //System.out.println(jsonObject.toString());
//		                    throw new RuntimeException("调用新零帮失败，进行回滚");
	                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
	                    return "error5";
	                }
				}
    		}
            _hxStorageMoveRecord.setReturnStatus("已完成");
            hxStorageMoveRecords.add(_hxStorageMoveRecord);
            if(hxStorageStock.getStockState().equals("待回传")) {
                boolean update = hxStoragePutDetailedService.lambdaUpdate()
                        .eq(HxStoragePutDetailed::getStockId, hxStorageStock.getId())
                        .set(HxStoragePutDetailed::getPositionNumber, _hxStorageMoveRecord.getNewPositionNumber())
                        .set(HxStoragePutDetailed::getPositionId, _hxStorageMoveRecord.getNewPositionId())
                        .set(HxStoragePutDetailed::getXlbPositionId, basicPosition.getPositionXlbId())
                        .update();
                if (!update){
                    throw new RuntimeException();
                }
            }
            if ("拣货位".equals(hxStorageStock.getPositionType())){
                List<HxStorageStock> stocks = stockService.lambdaQuery()
                        .notIn(HxStorageStock::getId, ids)
                        .ne(HxStorageStock::getStockState,"集货")
                        .eq(HxStorageStock::getPositionId, hxStorageStock.getPositionId())
                        .eq(HxStorageStock::getGoodsId, hxStorageStock.getGoodsId())
                        .eq(HxStorageStock::getWarehouseId,hxStorageStocks.get(0).getWarehouseId())
                        .list();
                if (ToolUtil.isEmpty(stocks)){
                    HxBasicPositionGoodsParam hxBasicPositionGoodsParam = new HxBasicPositionGoodsParam();
                    hxBasicPositionGoodsParam.setPositionId(hxStorageStock.getPositionId());
                    hxBasicPositionGoodsParam.setGoodsId(hxStorageStock.getGoodsId());
                    positionGoodsService.deleteByOne(hxBasicPositionGoodsParam);
                }
            }
            if ("拣货位".equals(basicPosition.getPositionType())){
                //完成库位表商品绑定
                HxBasicPositionGoodsParam positionGoodsParam = new HxBasicPositionGoodsParam();
                positionGoodsParam.setPositionId(Long.valueOf(basicPosition.getId()));
                positionGoodsParam.setPositionType("拣货位");
                positionGoodsParam.setGoodsId(hxStorageStock.getGoodsId());
                HxBasicPositionGoodsResult positionGoodsResult = positionGoodsService.findBySpec(positionGoodsParam);
                if (ToolUtil.isEmpty(positionGoodsResult)){
                    HxBasicPositionGoods hxBasicPositionGoods = new HxBasicPositionGoods();
                    hxBasicPositionGoods.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
                    hxBasicPositionGoods.setAreaId(_hxStorageMoveRecord.getAreaId());
                    hxBasicPositionGoods.setAreaName(basicPosition.getPositionAreaName());
                    hxBasicPositionGoods.setPositionId(_hxStorageMoveRecord.getNewPositionId());
                    hxBasicPositionGoods.setPositionNumber(_hxStorageMoveRecord.getNewPositionNumber());
                    hxBasicPositionGoods.setPositionPickingorder(basicPosition.getPositionPickingorder());
                    hxBasicPositionGoods.setGoodsId(_hxStorageMoveRecord.getGoodsId());
                    hxBasicPositionGoods.setGoodsName(_hxStorageMoveRecord.getGoodsName());
                    hxBasicPositionGoods.setGoodsNumber(_hxStorageMoveRecord.getGoodsNumber());
                    hxBasicPositionGoods.setGoodsPcode69(_hxStorageMoveRecord.getGoodsPcode69());
                    hxBasicPositionGoods.setGoodsSpecs(hxStorageStock.getGoodsSpecs());
                    HxBasicGoods basicGoods = goodsService.getById(_hxStorageMoveRecord.getGoodsId());
                    hxBasicPositionGoods.setAnquanNum(basicGoods.getAnquanNum());
                    hxBasicPositionGoods.setPsUnit(hxStorageStock.getPsUnit());
                    hxBasicPositionGoods.setPsRate(hxStorageStock.getPsRate());
                    hxBasicPositionGoods.setJibenUnit(hxStorageStock.getJibenUnit());
                    hxBasicPositionGoods.setOperator(user.getName());
                    positionGoodsService.save(hxBasicPositionGoods);
                }
            }
        }
        if (ToolUtil.isNotEmpty(hxStorageMoveRecords)){
            boolean b = saveBatch(hxStorageMoveRecords);
            if (!b){
                throw new RuntimeException();
            }
            boolean update = stockService.lambdaUpdate()
                    .in(HxStorageStock::getId, longs)
                    .set(HxStorageStock::getPositionNumber, hxStorageMoveRecord.getNewPositionNumber())
                    .set(HxStorageStock::getPositionType, hxStorageMoveRecord.getNewPositionType())
                    .set(HxStorageStock::getPositionId, hxStorageMoveRecord.getNewPositionId())
                    .set(HxStorageStock::getAreaId, hxStorageMoveRecord.getAreaId())
                    .set(HxStorageStock::getAreaNumber, basicPosition.getAreaNumber())
                    .set(HxStorageStock::getAreaName, basicPosition.getPositionAreaName())
                    .set(HxStorageStock::getTransferTime, LocalDateTime.now())
                    .update();
            if (!update){
                throw new RuntimeException();
            }
            return ""+longs.size();
        }
        return "error";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData storageMoveCnt(StorageMoveCntVo storageMoveCntVo) {
        User user = userAop.getUser();
        Map<String,StorageMoveCntItemVo> storageMoveCntItemMap = new HashMap();
        for(StorageMoveCntItemVo obj : storageMoveCntVo.getMoveItem()){
            if(obj.getZyNum().compareTo(BigDecimal.ZERO) < 1){
                return ResponseData.error("移库数量必须大于0！！！");
            }
            storageMoveCntItemMap.put(obj.getId().toString(),obj);
        }
        List<HxStorageStock> hxStorageStockList = stockService.lambdaQuery()
                .in(HxStorageStock::getId, storageMoveCntItemMap.keySet())
                .last(" for update ")
                .list();
        if(ToolUtil.isEmpty(hxStorageStockList)){
            return ResponseData.error("选择的库存不存在，请刷新后重试！！！");
        }

        BasicPosition basicPosition;
        if(storageMoveCntVo.getNewPositionId() != null) {
            basicPosition = positionService.lambdaQuery()
                    .eq(BasicPosition::getWarehouseId, hxStorageStockList.get(0).getWarehouseId())
                    .eq(BasicPosition::getId, storageMoveCntVo.getNewPositionId())
                    .last("LIMIT 1")
                    .one();
        } else {
            basicPosition = positionService.lambdaQuery()
                    .eq(BasicPosition::getWarehouseId, hxStorageStockList.get(0).getWarehouseId())
                    .eq(BasicPosition::getPositionNumber, storageMoveCntVo.getNewPositionNumber())
                    .last("LIMIT 1")
                    .one();
        }

        if(ToolUtil.isEmpty(basicPosition)){
            return ResponseData.error("目标库位不存在！！！");
        }

        List<HxStorageMoveRecord> hxStorageMoveRecords=new ArrayList<>();
        HxStorageMoveRecord _hxStorageMoveRecord = null;

        List<HxStorageStock> chafenList = new ArrayList<>();
        List<HxStorageStock> updateList = new ArrayList<>();
        // 判断输入数量是否超出，库存数量，若超出则报错，无超出则添加拆分记录
        for(HxStorageStock obj : hxStorageStockList){
            if(Long.compare(obj.getPositionId(),basicPosition.getId()) == 0){
                return ResponseData.error("原库位不能目标库位一样！！！");
            }

            StorageMoveCntItemVo storageMoveCntItemVo = storageMoveCntItemMap.get(obj.getId().toString());
            int zyFlag = storageMoveCntItemVo.getZyNum().compareTo(new BigDecimal(obj.getKcNum()));
            if(zyFlag > 0){
                return ResponseData.error("转移数量超出库存数量，请刷新后重试！！！");
            }else if(zyFlag < 0){
                BigDecimal subtract = new BigDecimal(obj.getKcNum()).subtract(storageMoveCntItemVo.getZyNum());
                obj.setKcNum(subtract.toString());
                obj.setJibenNum(subtract.multiply(new BigDecimal(obj.getKcRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN));
                obj.setStockVolume(subtract.multiply(new BigDecimal(obj.getGoodsVolume())).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
                obj.setStockWeight(subtract.multiply(new BigDecimal(obj.getGoodsWeight())).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                obj.setStockMoney(subtract.multiply(new BigDecimal(obj.getGoodsPrice())).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                chafenList.add(obj);
                HxStorageStock newStorageStock = new HxStorageStock();
                ToolUtil.copyProperties(obj, newStorageStock);
                newStorageStock.setKcNum(storageMoveCntItemVo.getZyNum().toString());
                newStorageStock.setPositionId(basicPosition.getId().longValue());
                newStorageStock.setPositionNumber(basicPosition.getPositionNumber());
                newStorageStock.setPositionType(basicPosition.getPositionType());
                newStorageStock.setJibenNum(storageMoveCntItemVo.getZyNum().multiply(new BigDecimal(obj.getKcRate())));
                newStorageStock.setStockVolume(storageMoveCntItemVo.getZyNum().multiply(new BigDecimal(obj.getGoodsVolume())).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
                newStorageStock.setStockWeight(storageMoveCntItemVo.getZyNum().multiply(new BigDecimal(obj.getGoodsWeight())).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                newStorageStock.setStockMoney(storageMoveCntItemVo.getZyNum().multiply(new BigDecimal(obj.getGoodsPrice())).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                newStorageStock.setAreaId(basicPosition.getPositionAreaId().longValue());
                newStorageStock.setAreaName(basicPosition.getPositionAreaName());
                newStorageStock.setAreaNumber(basicPosition.getAreaNumber());
                newStorageStock.setWarehouseId(basicPosition.getWarehouseId().longValue());
                newStorageStock.setWarehouseName(basicPosition.getWarehouseName());
                newStorageStock.setId(null);
                chafenList.add(newStorageStock);
            }else {
                obj.setPositionId(basicPosition.getId().longValue());
                obj.setPositionNumber(basicPosition.getPositionNumber());
                obj.setPositionType(basicPosition.getPositionType());
                obj.setAreaId(basicPosition.getPositionAreaId().longValue());
                obj.setAreaName(basicPosition.getPositionAreaName());
                obj.setAreaNumber(basicPosition.getAreaNumber());
                obj.setWarehouseId(basicPosition.getWarehouseId().longValue());
                obj.setWarehouseName(basicPosition.getWarehouseName());
                updateList.add(obj);
            }
            _hxStorageMoveRecord = new HxStorageMoveRecord();
            _hxStorageMoveRecord.setOperateId(obj.getOperateId());
            _hxStorageMoveRecord.setCustomerId(obj.getCustomerId());
            _hxStorageMoveRecord.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
            _hxStorageMoveRecord.setWarehouseName(basicPosition.getWarehouseName());
            _hxStorageMoveRecord.setAreaId(Long.valueOf(basicPosition.getPositionAreaId()));
            _hxStorageMoveRecord.setOldPositionId(obj.getPositionId());
            _hxStorageMoveRecord.setOldPositionNumber(obj.getPositionNumber());
            _hxStorageMoveRecord.setOldPositionType(obj.getPositionType());
            _hxStorageMoveRecord.setNewPositionId(Long.valueOf(basicPosition.getId()));
            _hxStorageMoveRecord.setNewPositionType(basicPosition.getPositionType());
            _hxStorageMoveRecord.setNewPositionNumber(basicPosition.getPositionNumber());
            _hxStorageMoveRecord.setTrayId(obj.getTrayId());
            _hxStorageMoveRecord.setTrayNumber(obj.getTrayNumber());
            _hxStorageMoveRecord.setGoodsId(obj.getGoodsId());
            _hxStorageMoveRecord.setGoodsName(obj.getGoodsName());
            _hxStorageMoveRecord.setGoodsNumber(obj.getGoodsNumber());
            _hxStorageMoveRecord.setGoodsPcode69(obj.getGoodsPcode69());
            _hxStorageMoveRecord.setGoodsSpecs(obj.getGoodsSpecs());
            _hxStorageMoveRecord.setKcUnit(obj.getKcUnit());
            _hxStorageMoveRecord.setKcNum(storageMoveCntItemVo.getZyNum().toString());
            _hxStorageMoveRecord.setTransferTime(LocalDateTime.now());
            _hxStorageMoveRecord.setDeptId(obj.getDeptId());
            _hxStorageMoveRecord.setReturnStatus("已完成");
            _hxStorageMoveRecord.setTransferUser(user.getAccount());
            _hxStorageMoveRecord.setTransferUserId(user.getUserId());
            hxStorageMoveRecords.add(_hxStorageMoveRecord);
        }
        if (ToolUtil.isNotEmpty(hxStorageMoveRecords)) {
            boolean b = saveBatch(hxStorageMoveRecords);
            if(b){
                // 拆分库存
                if(chafenList.size() > 0){
                    stockService.saveOrUpdateBatch(chafenList);
                }
                if(updateList.size() > 0){
                    stockService.saveOrUpdateBatch(updateList);
                }
            }
        }
        return ResponseData.success();
    }

    @Override
    public void deleteByTime(String format) {
        this.baseMapper.deleteByTime(format);
    }

    private Serializable getKey(HxStorageMoveRecordParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxStorageMoveRecord getOldEntity(HxStorageMoveRecordParam param) {
        return this.getById(getKey(param));
    }

    private HxStorageMoveRecord getEntity(HxStorageMoveRecordParam param) {
        HxStorageMoveRecord entity = new HxStorageMoveRecord();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

	@Override
	public List<String> findOutTask(Long id) {
		return this.baseMapper.findOutTask(id);
	}

	@Override
	public HxStorageMoveRecordResult count(HxStorageMoveRecordParam hxStorageMoveRecordParam, Long operateId,
			String condition) {
		return this.baseMapper.count(hxStorageMoveRecordParam,operateId,condition);
	}

	@Override
	public List<HxStorageMoveRecordResult> listAll(HxStorageMoveRecordParam hxStorageMoveRecordParam, Long operateId,
			String condition) {
		return this.baseMapper.listAll(hxStorageMoveRecordParam,operateId,condition);
	}

    @Override
    public LayuiPageInfo selectUser(HxStorageMoveRecordParam hxStorageMoveRecordParam, String condition) {
        Page pageContext = getPageContext();
        IPage qualityuser = this.baseMapper.selectuser(pageContext,hxStorageMoveRecordParam,condition);
        return   LayuiPageFactory.createPageInfo(qualityuser);
    }

}
